package net.xujialiang.XTestRPA.Service.RPA;

import net.xujialiang.XTestRPA.Entity.RPA.XRPATaskDetail;
import net.xujialiang.XTestRPA.Repository.RPA.RPATaskDetailRepository;
import net.xujialiang.XTestRPA.Service.Tenant.XRPATenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class XRPADetailService {
    @Autowired
    RPATaskDetailRepository taskDetailRepository;
    @Autowired
    XRPAPointService pointService;
    @Autowired
    XRPATenantService tenantService;

    /**
     * 新增执行任务详情
     * @param reqData 请求数据
     */
    public void create(Map<String, Object> reqData, String createAccount, String ttc) throws Exception {
        String taskId = (String) reqData.get("taskId");
        String taskName = (String) reqData.get("taskName");
        String taskStatus = (String) reqData.get("taskStatus");
        long executeStart = (long) reqData.get("executeStart");
        long executeEnd = (long) reqData.get("executeEnd");
        String executeLogID = (String) reqData.get("executeLogID");
        XRPATaskDetail entity = XRPATaskDetail.builder()
                .taskID(taskId)
                .executeBy(createAccount)
                .taskName(taskName)
                .ttc(ttc)
                .taskStatus(taskStatus)
                .executeStart(new Timestamp(executeStart))
                .executeEnd(new Timestamp(executeEnd))
                .executeLogID(executeLogID)
                .createTime(new Timestamp(System.currentTimeMillis()))
                .build();

        taskDetailRepository.save(entity);

//        int costPoint = (int) reqData.get("costPoint");
//        pointService.costPoint(taskId, taskName, costPoint, "消耗", createAccount, ttc);
//        tenantService.costPoints(costPoint,ttc);
    }

    /**
     * 分页获取分组数据
     * @param page 页码
     * @param pageSize 每页条数
     * @return
     */
    public Map<String, Object> fetchByPage(String ttc, int page, int pageSize) {
        Sort sort = Sort.by(Sort.Direction.DESC,  "id");
        PageRequest pr =  PageRequest.of(page,pageSize, sort);
        Page<XRPATaskDetail> pageData = taskDetailRepository.findAllByTtc(ttc, pr);
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("totalPages", pageData.getTotalPages());
        ret.put("totalCount", pageData.getTotalElements());
        ret.put("page", page);
        ret.put("pageSize", pageSize);
        ret.put("list", pageData.getContent());
        return ret;
    }
}
